package com.woniu.zsd.merchant.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.client.PermissionClient;
import com.woniu.client.UserClient;
import com.woniu.commons.util.RedisKey;
import com.woniu.dto.UserDto;
import com.woniu.dto.ReplyListDto;
import com.woniu.form.AddCommentForm;
import com.woniu.form.QueryReplyForm;
import com.woniu.zsd.commons.core.model.Result;
import com.woniu.zsd.commons.exception.ZsdException;
import com.woniu.zsd.merchant.entity.Reply;
import com.woniu.zsd.merchant.mapper.ReplyMapper;
import com.woniu.zsd.merchant.service.IReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.zsd.merchant.util.DateTimeUtil;
import com.woniu.zsd.merchant.util.MerchartTokenUtil;
import com.woniu.zsd.order.client.ZsdOrderClient;
import com.woniu.zsd.permission.entity.AdminInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.PipedReader;
import java.util.List;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@Service
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply> implements IReplyService {

    @Resource
    private ReplyMapper replyMapper;

    @Autowired
    private MerchartTokenUtil tokenUtil;

    @Autowired
    private UserClient userClient;

    @Autowired
    private PermissionClient permissionClient;

//    @Autowired
//    private ZsdOrderClient zsdOrderClient;
    @Resource
    private ZsdOrderClient zsdOrderClient;

    @Autowired
    private SiteServiceImpl siteServiceImpl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Page<ReplyListDto> replyList(QueryReplyForm queryReplyForm) {
        Page<Reply> page = new Page<>(queryReplyForm.getPageNum()==null? 1: queryReplyForm.getPageNum(),
                                      queryReplyForm.getPageSize()==null ? 5: queryReplyForm.getPageSize());
        DateTime startTime = null;
        DateTime endTime = null;
        if (!StringUtils.isBlank(queryReplyForm.getStartTime())) {
            startTime = DateTimeUtil.stringToDateTime(queryReplyForm.getStartTime());
        }
        if (!StringUtils.isBlank(queryReplyForm.getEndTime())) {
            endTime = DateTimeUtil.stringToDateTime(queryReplyForm.getEndTime());
        }
        Page<ReplyListDto> replyPage = replyMapper.replyList(page, queryReplyForm.getContent(), startTime, endTime, queryReplyForm.getSiteId());
        // 获取userId set集合
        Set<Integer> userIds = new HashSet<>();
        for (ReplyListDto reply : replyPage.getRecords()) {
            userIds.add(reply.getUserId());
        }
        // 获取 set集合
        Set<Integer> adminIds = new HashSet<>();
        for (ReplyListDto reply : replyPage.getRecords()) {
            adminIds.add(reply.getDirectorId());
        }
        Result<List<UserDto>> userResult = null;
        Result<List<AdminInfo>> adminResult = null;
        if (!userIds.isEmpty()) {
            System.out.println(userIds);
            userResult = userClient.selUserInfoByIds(userIds);
            System.out.println(userResult.toString());
        }
        if (!adminIds.isEmpty()) {
            adminResult = permissionClient.selectAdminInfoByIds(adminIds);
            System.out.println(adminResult);
        }

        for (ReplyListDto reply : replyPage.getRecords()) {
            if (reply.getUserId() != null) {
                if (userResult != null) {
                    for (UserDto user : userResult.getData()) {
                        if (Objects.equals(user.getId(), reply.getUserId())) {
                            reply.setUserNickName(user.getNickName());
                            reply.setUserHeadPath(user.getHeadImage());
                        }
                    }
                }
            } else if (reply.getDirectorId() != null) {
                if (adminResult != null) {
                    for (AdminInfo admin : adminResult.getData()) {
                        if (Objects.equals(admin.getAdminId(), reply.getDirectorId())) {
                            reply.setDirectorName(admin.getName());
                            reply.setDirectorHeadPath(admin.getHeadPath());
                        }
                    }
                }
            }
        }

        return replyPage;
    }

    @Override
    public void addComment(AddCommentForm addCommentForm, String token) {
        System.out.println(token);
        if (addCommentForm.getCommentId() != null && addCommentForm.getParentId() != null){
            if (addCommentForm.getCommentId() == addCommentForm.getParentId()){
                throw new ZsdException("评论失败", 30001);
            }
        }
        if (addCommentForm.getParentId()!=null) {
            if (addCommentForm.getCommentId()==null){
                throw new ZsdException("评论失败", 30001);
            }
        }
        QueryWrapper<Reply> queryWrapper = new QueryWrapper<>();
        if (addCommentForm.getCommentId()!=null) {
            //可能是父评论
            Reply reply = replyMapper.selectById(addCommentForm.getCommentId());
            if (reply == null) throw new ZsdException("评论失败", 30001);
            if (!Objects.equals(reply.getSiteId(), addCommentForm.getSiteId())){
                throw new ZsdException("评论失败", 30001);
            }
            if (addCommentForm.getParentId()!=null){
                //说明是子评论
                reply = replyMapper.selectById(addCommentForm.getParentId());
                if (reply == null) throw new ZsdException("评论失败", 30001);
                if (!Objects.equals(reply.getSiteId(), addCommentForm.getSiteId())){
                    throw new ZsdException("评论失败", 30001);
                }
                //父评论和留言的评论id一致
                if (!Objects.equals(reply.getCommentId(), addCommentForm.getCommentId())){
                    throw new ZsdException("评论失败", 30001);
                }
            }
        }

        Integer userId = null;
        Integer adminId = null;
        // 判断是谁的 token
        try {
            if (stringRedisTemplate.hasKey(RedisKey.USER_REFRESH_TOKEN_KEY(token))){
                userId = tokenUtil.getUserId(token);
            }else {
                adminId = tokenUtil.getAdminId(token);
            }
        }catch (Exception e){
            throw new ZsdException("token无效", 30001);
        }

        System.out.println(userId);
        System.out.println(addCommentForm.getSiteId());
        if (userId != null) {
            if(!zsdOrderClient.isOrderFinish(userId, addCommentForm.getSiteId())) {
                throw new ZsdException("未完成该站点订单，无法评论", 20001);
            };
        } else {
            Set<Integer> adminIds = new HashSet<>();
            adminIds.add(adminId);
            AdminInfo adminInfo = permissionClient.selectAdminInfoByIds(adminIds).getData().get(0);
            System.out.println("adminSiteId:"+adminInfo.getSiteId());
            System.out.println("formSiteId:"+addCommentForm.getSiteId());
            if (adminInfo.getRole() != 5 && !Objects.equals(adminInfo.getSiteId(), addCommentForm.getSiteId())) {
                throw new ZsdException("你无法评价其他站点的留言", 20002);
            }
        }

        DateTime creatTime = DateTime.now();

        if (addCommentForm.getCommentId() == null) {
            // 添加站点评论
            replyMapper.addComment(userId, adminId, addCommentForm.getSiteId(), creatTime, addCommentForm.getContent());
        } else if (addCommentForm.getParentId() == null) {
            //添加评论回复
            replyMapper.addReply(userId, adminId, addCommentForm.getSiteId(), addCommentForm.getCommentId(), creatTime, addCommentForm.getContent());
        } else {
            //添加评论回复的子回复
            replyMapper.addSubReply(userId, adminId, addCommentForm.getSiteId(), addCommentForm.getCommentId(), addCommentForm.getParentId(), creatTime, addCommentForm.getContent());
        }
    }

    @Override
    public void deleteReply(Integer id, String token) {
        if (id == null) {
            throw new ZsdException("回复不存在", 20001);
        }

        Integer userId = null;
        Integer adminId = null;
        // 判断是谁的 token

        if (stringRedisTemplate.hasKey(RedisKey.USER_REFRESH_TOKEN_KEY(token))){
            userId = tokenUtil.getUserId(token);
            //是用户删除只能删除自己的留言和子留言
            // 查询当前 id 对应的回复信息
            Reply reply = replyMapper.selectById(id);
            if (reply == null) {
                throw new ZsdException("回复不存在", 20001);
            }

            if (!Objects.equals(reply.getUserId(), userId)){
                throw new ZsdException("你无法删除其他用户的回复", 20002);
            }

            // 删除逻辑
            replyDelete(id, reply);
        }else {
            adminId = tokenUtil.getAdminId(token);
            Set<Integer> adminIds = new HashSet<>();
            adminIds.add(adminId);
            AdminInfo adminInfo = permissionClient.selectAdminInfoByIds(adminIds).getData().get(0);

            // 查询当前 id 对应的回复信息
            Reply reply = replyMapper.selectById(id);
            if (reply == null) {
                throw new ZsdException("回复不存在", 20001);
            }

            System.out.println("adminSiteId:"+adminInfo.getSiteId()+":"+reply.getSiteId());
            if (adminInfo.getRole() != 5 && !Objects.equals(adminInfo.getSiteId(), reply.getSiteId())) {
                throw new ZsdException("你无法删除其他站点的回复", 20003);
            }

            if (adminInfo.getRole() != 5 && adminInfo.getRole() != 2 && !Objects.equals(adminInfo.getSiteId(), reply.getSiteId())) {
                throw new ZsdException("你无法删除其他用户的回复", 20002);
            }

            // 删除逻辑
            replyDelete(id, reply);
        }
    }

    private void replyDelete(Integer id, Reply reply) {
        if (reply.getParentId() != null) {
            // 是子评论，删除该评论
            replyMapper.deleteById(id);
        } else if (reply.getCommentId() != null) {
            // 删除父评论以及父评论下的所有子评论
            QueryWrapper<Reply> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", id).or().eq("reply_id", id);
            replyMapper.delete(wrapper);
            replyMapper.deleteById(id);
        } else {
            QueryWrapper<Reply> wrapper = new QueryWrapper<>();
            wrapper.eq("comment_id", id).or().eq("reply_id", id);
            replyMapper.delete(wrapper);
        }
    }
}
